package controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONArray;
import org.json.JSONObject;

import domain.POS;

/**
 * Servlet implementation class AJAXCotroller
 */
public class AJAXCotroller extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AJAXCotroller() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String todo = request.getParameter("todo");
		
		if(todo.equals("getPOS")){
			
			POS pos = new POS();
			pos.setName("BTNC heuartead qr");
			pos.setLatitute(13.711428);
			pos.setLongtitute(100.594103);
			
			POS pos2 = new POS();
			pos2.setName("The Mall Ramkhamhaeng 3");
			pos2.setLatitute(13.752729);
			pos2.setLongtitute(100.609644);
			
			POS pos3 = new POS();
			pos3.setName("Seconsquare");
			pos3.setLatitute(13.695265);
			pos3.setLongtitute(100.648187);
			
			POS pos4 = new POS();
			pos4.setName("Central Department Store");
			pos4.setLatitute(13.669594);
			pos4.setLongtitute(100.634778);
			
			
			ArrayList<POS> posList = new ArrayList<POS>();
			posList.add(pos);
			posList.add(pos2);
			posList.add(pos3);
			posList.add(pos4);
			
			JSONObject json = createPosJSON(posList);
			  
			response.setContentType("application/json");
			PrintWriter out = response.getWriter();
			out.print(json);
			out.flush();
		}
	}
	
	public JSONObject createPosJSON(ArrayList<POS> posList){
		JSONObject j = new JSONObject();
		JSONArray jsonArray = new JSONArray();
		  for (int i=0; i<posList.size(); i++) {
			  JSONObject json = new JSONObject();
			  POS posTemp = posList.get(i);
			  json.put("name", posTemp.getName());
			  json.put("lat", posTemp.getLatitute());
			  json.put("lng", posTemp.getLongtitute());
			  jsonArray.put(json);
		  }
		j.put("pos", jsonArray);
		return j;
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}
